# -*- coding: utf-8 -*-

import sqlite3
import time
import logging
from conf_funs import get_task_message
from weixin_modules.inner_settings import *
logger = logging.getLogger('uiauto_weixin.weixin_modules.oper_database')


# 创建sqlite3 数据库，创建表
# 读数据库，
# 写数据库
# 查询 插入等，

# 1库，放好友信息，
# 2库，放群信息，
# 3库，放聊天记录，

# 数据库的路径，
# example:
# C:\Users\daqiao\PycharmProjects\uiauto_weixin\users\db\friendinfo.db
wx_db_dir = "db"
friendinfo_filename = "friendinfo.db"
task_filename = "task.db"

class OperDatabase(object):

    def __init__(self, wxid):
        # 检查文件夹是否存在，不存在则创建，，
        db_path = os.path.join(users_config_dir, wxid, wx_db_dir)
        if not os.path.exists(db_path):
            os.makedirs(db_path)
        self.friendinfo_db_path = os.path.join(db_path, friendinfo_filename)
        self.task_db_path = os.path.join(db_path, task_filename)
        # 初始化数据库，s
        self.init_db()
        # 打开 2个数据库，方便操作，
        self.friendinfo_db = sqlite3.connect(self.friendinfo_db_path)
        self.task_db = sqlite3.connect(self.task_db_path)

    def init_db(self):
        """
        检查数据库是否存在，
        不存在则创建
        :return:
        """
        if not os.path.exists(self.friendinfo_db_path):
            self.init_friendinfo_db()
        if not os.path.exists(self.task_db_path):
            self.init_task_db()

    def init_friendinfo_db(self):
        """
        初始化数据库 friendinfo_db
        :return:
        """

        conn = sqlite3.connect(self.friendinfo_db_path)
        logger.debug("friendinfo_db 数据库创建成功!")
        c = conn.cursor()

        # 创建表 t_user
        c.execute('''CREATE TABLE t_user
                   (tag_id INTEGER PRIMARY KEY NOT NULL,
                   nick_name TEXT NOT NULL,
                   wxid TEXT NOT NULL)''')
        logger.debug("数据表创建成功")

        # 创建表 t_friendinfo
        c.execute("""create table main.t_friend
                (
                    id              INTEGER
                        primary key autoincrement,
                    wxid            TEXT not null,
                    friend_serialno INT  NOT NULL,
                    wx_alias        TEXT not null,
                    nick_name       TEXT not null,
                    area            TEXT not null,
                    update_time     INT  not null,
                    status          INT  not null,
                    tag_id          INT  not null,
                    frequency       INT  not null
                );""")

        # 创建表 t_business_friend
        c.execute("""CREATE TABLE t_business_friend
                    (id INTEGER PRIMARY KEY   AUTOINCREMENT,
                    company TEXT NOT NULL ,
                    wx_alias TEXT NOT NULL ,
                    nick_name TEXT NOT NULL ,
                    active INT NOT NULL ,
                    update_time INT NOT NULL,
                    status INT NOT NULL,
                    tag_id INT NOT NULL,
                    frequency INT NOT NULL
                    )""")
        # 创建表 t_public_accounts 放入公众号名
        c.execute("""CREATE TABLE t_public_accounts
                    (id INTEGER PRIMARY KEY   AUTOINCREMENT,
                    accounts TEXT NOT NULL ,
                    tag_id INT NOT NULL)""")
        # 创建表 t_rooms，微信群的信息，
        c.execute("""create table main.t_rooms
                    (
                        id                 INTEGER
                            primary key autoincrement,
                        tag_id             INT  not null,
                        room_serialno      INT  not null,
                        room_alias         TEXT,
                        room_name          TEXT not null,
                        roomid             TEXT,
                        roomowner_alias    TEXT,
                        roomowner_nick     TEXT not null,
                        roomowner_wxid     TEXT,
                        roomowner_area     TEXT,
                        roomtype           INT  not null,
                        company            TEXT,
                        members_total      INT  not null,
                        creation_time      INT  not null,
                        creation_time_text TEXT,
                        update_time        INT,
                        update_time_text   TEXT,
                        status             INT  not null,
                        area               INT  not null
                    );""")
        c.execute("""
                    create table main.t_room_members
                    (
                        id            INTEGER
                            primary key autoincrement,
                        tag_id        INT  not null,
                        room_serialno INT  not null,
                        wx_alias      TEXT,
                        nick_name     TEXT not null,
                        wxid          TEXT,
                        area          TEXT
                    );""")

        c.execute("""
                    create table main.t_records_manage
                (
                    id          integer not null
                        primary key autoincrement,
                    tag_id      integer not null,
                    room_name   TEXT    not null,
                    counts      TEXT    not null,
                    update_time TEXT    not null
                );
        """)

        conn.commit()
        c.close()
        conn.close()

    def init_task_db(self):
        """
        初始化数据库 task_db
        :return:
        """
        conn = sqlite3.connect(self.task_db_path)
        logger.debug("friendinfo_db 数据库创建成功!")
        c = conn.cursor()
        c.execute("""
                    create table main.rooms_task
                    (
                        id               INTEGER
                            primary key autoincrement,
                        tag_id           INT  not null,
                        task_type        INT  not null,
                        task_id          INT  not null,
                        content          TEXT,
                        total            INT  not null,
                        create_time      INT  not null,
                        create_time_text TEXT not null,
                        update_time      INT,
                        update_time_text TEXT,
                        status           INT  not null
                    );
                    """)
        c.execute("""
                    create table main.rooms_records
                    (
                        id               INTEGER
                            primary key autoincrement,
                        tag_id           INT  not null,
                        task_id          INT  not null,
                        room_alias       TEXT not null,
                        update_time      INT,
                        update_time_text TEXT,
                        status           INT not null
                    );
                    """)

        conn.commit()
        c.close()
        conn.close()

    # def __del__(self):
    #     self.friendinfo_db.close()
    #     self.task_db.close()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.friendinfo_db.close()
        self.task_db.close()

    def close(self):
        self.friendinfo_db.close()
        self.task_db.close()

    def select_user(self, nick_name, wxid):
        """
        查询用户信息，返回tag_id,
        没有则插入
        :return:
        """
        c = self.friendinfo_db.cursor()
        # tag_id 的默认值，初始值为 1001
        tag_id = 1001
        # 从数据库中查询，是否存在，
        sql = f"SELECT tag_id FROM t_user WHERE wxid LIKE '%{wxid}%'"
        c.execute(sql)
        values = c.fetchone()
        if values:
            tag_id = values[0]
        else:
            sql = "SELECT MAX(tag_id) FROM t_user"
            c.execute(sql)
            values = c.fetchone()
            if values[0] is None:
                # 数据库是空的，没有数据，写入数据
                sql = f"INSERT INTO t_user (tag_id, nick_name, wxid) VALUES('{tag_id}','{nick_name}','{wxid}')"
            else:
                # 数据库中有数据 ，tag_id 加1，写入
                tag_id = values[0] + 1
                sql = f"INSERT INTO t_user (tag_id, nick_name, wxid) VALUES('{tag_id}','{nick_name}','{wxid}')"
            c.execute(sql)
            self.friendinfo_db.commit()
            c.close()
        return tag_id

    def select_friends(self, tag_id):
        """
        查询库中的当前用户下的 好友名字列表，
        :return:
        """
        c = self.friendinfo_db.cursor()
        value_set = set()
        sql = f"SELECT wx_alias, nick_name FROM t_friend WHERE tag_id = '{tag_id}'"
        logger.debug(sql)
        c.execute(sql)
        values = c.fetchall()
        c.close()
        for value in values:
            value_set.add(value[0])
            value_set.add(value[1])
        return value_set

    def insert_friend_info(self, friend_info):
        """
        把生成的好友信息字典 插入 数据库

        加入几个参数，
        update_time，更新时间
        status，状态（1在通讯录中，2不在，0未知）
        frequency，沟通频率，

         friend_info 的数据格式
         {
             "nick_name": nick_name,
             "wx_alias": wx_alias,
             "wxid": wxid,
             "area": area,
             "tag_id": self.tag_id,
             "update_time": int(time.time()),
             "status": 1,
             "frequency": 0
         }
        :param friend_info_list:
        :return:
        """
        # wxid 也可以变更，但是一般很少换，
        c = self.friendinfo_db.cursor()
        sql = "SELECT nick_name FROM t_friend WHERE tag_id = '{tag_id}' AND wxid = '{wxid}'".format(**friend_info)
        c.execute(sql)
        values = c.fetchone()
        # 有可能好友换名字了，以wxid为标准判断，是否已经存在于数据库，
        # 存在则更新，不存在则插入，
        if values:
            # 存在则更新
            sql = """
                    UPDATE t_friend
                    SET friend_serialno='{friend_serialno}',
                        wx_alias       = '{wx_alias}',
                        nick_name      = '{nick_name}',
                        area           = '{area}',
                        update_time='{update_time}'
                    WHERE tag_id = '{tag_id}'
                      AND wxid = '{wxid}'
                    """.format(**friend_info)
        else:
            # 不存在，则插入
            sql = """INSERT INTO t_friend (wxid, friend_serialno, wx_alias, nick_name, area, update_time, status, tag_id, frequency)
                        values ('{wxid}', '{friend_serialno}', '{wx_alias}', '{nick_name}', '{area}', '{update_time}', '{status}', '{tag_id}',
                                '{frequency}')""".format(**friend_info)
        # logger.debug(sql)
        c.execute(sql)
        self.friendinfo_db.commit()
        c.close()

    def select_business_friends(self, tag_id):
        """
        从数据库中查询企业好友的名字，返回好友名字的列表，
        # 也可以用名字来数据库中，一个一个的查询，先不这样做，
        :param tag_id:
        :return:
        """
        value_set = set()
        sql = f"SELECT wx_alias, nick_name FROM t_business_friend WHERE tag_id = '{tag_id}'"
        logger.debug(sql)
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        values = c.fetchall()
        c.close()
        for value in values:
            value_set.add(value[0])
            value_set.add(value[1])
        return value_set

    def insert_business_friends(self, info_dict):
        """
        把生成的企业好友信息插入 数据库
        :param info_dict:
        :return:
        """
        sql = """SELECT *
                FROM t_business_friend
                WHERE tag_id = '{tag_id}'
                  AND company = '{company}'
                  AND nick_name = '{nick_name}'
                """.format(**info_dict)
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        values = c.fetchone()
        # 有可能好友换名字了，以wxid为标准判断，是否已经存在于数据库，
        # 存在则更新，不存在则插入，
        if values:
            # 存在则更新
            sql = """UPDATE t_business_friend
                    SET wx_alias    = '{wx_alias}',
                        active      = '{active}',
                        update_time = '{update_time}'
                    WHERE tag_id = '{tag_id}'
                    """.format(**info_dict)
        else:
            # 不存在，则插入
            sql = """
            INSERT INTO t_business_friend (company, wx_alias, nick_name, active, update_time, status, tag_id, frequency) 
            VALUES ('{company}','{wx_alias}','{nick_name}','{active}','{update_time}','{status}','{tag_id}','{frequency}')
                """.format(**info_dict)
        c.execute(sql)
        self.friendinfo_db.commit()
        c.close()
        logger.debug("friend_info_insert:数据写入数据库")

    def insert_public_accounts(self, info_list):
        """
        公众号名字写入数据库，
        :param info_list:
        :return:
        """

        c = self.friendinfo_db.cursor()
        # info_list 的数据格式，[account, tag_id]
        for info in info_list:
            account = info[0]
            tag_id = info[1]
            sql = f"INSERT OR IGNORE INTO t_public_accounts(ACCOUNTS, TAG_ID) VALUES ('{account}', '{tag_id}')"
            c.execute(sql)
        self.friendinfo_db.commit()
        c.close()

    def select_public_accounts(self, tag_id):
        """
        从数据库，查询公众号的列表，
        :param tag_id:
        :return:
        """
        value_set = set()
        sql = f"SELECT accounts FROM t_public_accounts WHERE tag_id = '{tag_id}'"
        logger.debug(sql)
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        values = c.fetchall()
        c.close()
        for value in values:
            value_set.add(value[0])
        return value_set

    def select_rooms_info(self, tag_id):
        """
        从数据库中查询 群聊的名字，
        :param tag_id:
        :return:
        """
        value_set = set()
        sql = f"SELECT room_alias, room_name FROM t_rooms WHERE tag_id = '{tag_id}'"
        logger.debug(sql)
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        values = c.fetchall()
        c.close()
        for value in values:
            value_set.add(value[0])
            value_set.add(value[1])
        return value_set

    def insert_room_info(self, info_dict):
        """
        把 群的信息 写入数据库，
        :param info_dict:
        :return:
        """
        c = self.friendinfo_db.cursor()
        # 先判断 数据库中 是否 已经存在，
        sql = """
            SELECT room_name
            FROM t_rooms
            WHERE tag_id = '{tag_id}'
              AND room_name = '{room_name}'
              AND roomowner_nick = '{roomowner_nick}'
        """.format(**info_dict)
        c.execute(sql)
        value = c.fetchone()
        if value:
            logger.debug("insert_room_info 数据已存在，执行更新")
            sql = """
            UPDATE t_rooms
            SET room_serialno='{room_serialno}',
                room_alias='{room_alias}',
                members_total='{members_total}',
                update_time='{update_time}',
                update_time_text='{update_time_text}',
                status='{status}',
                area='{area}'
            WHERE tag_id = '{tag_id}'
              AND room_name = '{room_name}'
              AND roomowner_nick = '{roomowner_nick}'
            """.format(**info_dict)
        else:
            # 首次插入数据，update_time 就是 creation_time
            sql = """INSERT INTO t_rooms (tag_id, room_serialno, room_alias, room_name, roomid, roomowner_alias,
                         roomowner_nick, roomowner_wxid, roomowner_area, roomtype, company, members_total, creation_time,
                         creation_time_text, update_time, update_time_text, status, area)
                    VALUES ('{tag_id}', '{room_serialno}', '{room_alias}', '{room_name}', '{roomid}', '{roomowner_alias}',
            '{roomowner_nick}', '{roomowner_wxid}', '{roomowner_area}', '{roomtype}', '{company}', '{members_total}',
            '{update_time}', '{update_time_text}', '', '', '{status}', '{area}')""".format(**info_dict)
        # logger.debug(sql)
        c.execute(sql)
        self.friendinfo_db.commit()
        c.close()
        logger.debug("insert_room_info:数据写入数据库")

    def update_room_state(self, info_dict):
        """
        更新微信群的  状态，
        是否 还在群内，
        :param info_dict:
        :return:
        """
        logger.debug("update_room_state 更新微信群的状态")
        c = self.friendinfo_db.cursor()
        # 先判断 数据库中 是否 已经存在，
        sql = "SELECT room_name FROM t_rooms WHERE tag_id = '{tag_id}' AND room_alias = '{room_alias}'".format(
            **info_dict)
        c.execute(sql)
        value = c.fetchone()
        if value:
            logger.debug("update_room_state 数据已存在，执行更新")
            sql = """
                UPDATE t_rooms
                SET update_time='{update_time}',
                    update_time_text='{update_time_text}',
                    status='{status}'
                WHERE tag_id = '{tag_id}'
                  AND room_alias = '{room_alias}'
                  """.format(**info_dict)
            c.execute(sql)
            self.friendinfo_db.commit()
        c.close()

    def insert_room_members(self, room_serialno, members_list: list):
        """
        写入 t_room_members
        写入群成员信息，
        :param tag_id:
        :param room_name:
        :param member_info:
        :return:
        """
        c = self.friendinfo_db.cursor()
        for member in members_list:
            sql = """INSERT INTO t_room_members (tag_id, room_serialno, wx_alias, nick_name, wxid, area)
                    VALUES ('{tag_id}', '{room_serialno}', '{wx_alias}', '{nick_name}', '{wxid}', '{area}')"""
            sql = sql.format(room_serialno=room_serialno, **member)
            # logger.debug(sql)
            c.execute(sql)
        self.friendinfo_db.commit()
        c.close()

    def update_room_alias(self, tag_id, ori_alias, new_alias):
        """
        临时使用，主要是改备注名称
        :param tag_id:
        :param ori_alias:
        :param new_alias:
        :return:
        """
        c = self.friendinfo_db.cursor()
        # 先判断 数据库中 是否 已经存在，
        sql = f"SELECT room_name FROM t_rooms WHERE tag_id = '{tag_id}' AND room_alias = '{ori_alias}'"
        c.execute(sql)
        value = c.fetchone()
        if value:
            logger.debug("update_room_alias 数据已存在，执行更新")
            sql = f"UPDATE t_rooms SET room_alias='{new_alias}' WHERE tag_id='{tag_id}' AND room_alias='{ori_alias}'"
            logger.debug(sql)
            c.execute(sql)
            self.friendinfo_db.commit()
            logger.debug("update_room_alias:数据写入数据库")
        else:
            logger.debug("update_room_alias 数据不存在，跳过")
        c.close()

    def insert_rooms_records(self, info_dict_set):
        """
        把聊天记录空间管理 中的数据 写入t_records_manage
        :param info_dict_set:
        :return:
        """
        c = self.friendinfo_db.cursor()
        for info_dict in info_dict_set:
            sql = "INSERT INTO t_records_manage (tag_id, room_name, counts, update_time) " \
                  "VALUES ('{tag_id}', '{room_name}', '{count}', '{update_time}')".format(**info_dict)
            logger.debug(sql)
            c.execute(sql)
        self.friendinfo_db.commit()
        c.close()

    def select_task(self, tag_id, status):
        """
        数据库 task.db->t_task
        查询任务，

        :param tag_id:
        :param state:
        :return:
        """
        c = self.task_db.cursor()
        sql = "SELECT task_id, content, total, create_time_text FROM rooms_task WHERE tag_id='{}' AND status='{}'".format(
            tag_id, status)
        logger.debug(sql)
        c.execute(sql)
        result = c.fetchall()
        c.close()
        return result

    def get_last_task_id(self, tag_id):
        """
        获取当前用户下的最后一个 task_id
        :return:
        """
        c = self.task_db.cursor()
        sql = "SELECT MAX(task_id) FROM rooms_task WHERE tag_id='{}'".format(tag_id)
        logger.debug(sql)
        c.execute(sql)
        result = c.fetchone()
        c.close()
        task_id = result[0]
        if task_id is None:
            return 0
        return task_id

    def get_user_rooms_total(self, tag_id):
        """
        获取数据库中，指定 微信下 微信群的总数量 ，
        :param tag_id:
        :return:
        """
        sql = "SELECT count(room_alias) FROM t_rooms WHERE tag_id='{}' AND status='1'".format(tag_id)
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        result = c.fetchone()
        c.close()
        return result[0]

    def creat_task(self, task_info):
        """
        创建任务
        :param task_info:
        :return:
        """
        # 从数据库friendinfo的表t_rooms,中获取rooms列表，
        c = self.friendinfo_db.cursor()
        sql = "SELECT room_alias FROM t_rooms WHERE tag_id='{}' AND status='1'".format(task_info["tag_id"])
        logger.debug(sql)
        c.execute(sql)
        result = c.fetchall()
        total = len(result)
        logger.debug("共从数据库中找到微信群的数量：{}".format(total))
        c.close()

        # # # # # # # # # # # # # # # # # # # #
        c = self.task_db.cursor()
        sql = """INSERT INTO rooms_task (tag_id, task_type, task_id, content, total, create_time, create_time_text, status)
                VALUES ('{tag_id}', '{task_type}', '{task_id}', '{content}', '{total}','{create_time}', '{create_time_text}', '{status}')
        """.format(total=total, **task_info)
        logger.debug(sql)
        c.execute(sql)
        self.task_db.commit()
        c.close()

        # # # # # # # # # # # # # # # # # # # #
        # 并写入数据库task的表rooms_records中，
        c = self.task_db.cursor()
        task_rooms = []
        for room_alias_tuple in result:
            task_rooms.append(room_alias_tuple[0])
            sql = """INSERT INTO rooms_records (tag_id, task_id, room_alias, update_time, update_time_text, status)
                        VALUES ('{}', '{}', '{}', '', '', '0')
                    """.format(task_info["tag_id"], task_info["task_id"], room_alias_tuple[0])
            # logger.debug(sql)
            c.execute(sql)
        self.task_db.commit()
        c.close()
        return task_rooms

    def change_task_state(self, tag_id):
        """
        把所有未完成的任务，改为手动完成状态，
        :return:
        """
        # TODO:
        c = self.task_db.cursor()
        sql = "UPDATE t_task SET state='2' WHERE tag_id='{}'".format(tag_id)
        # logger.debug(sql)
        c.execute(sql)
        self.task_db.commit()
        c.close()

    def update_records(self, record_info):
        """
        更新表 t_reocrds

        :param record_info:
        :return:
        """
        c = self.task_db.cursor()
        sql = """
                UPDATE rooms_records
                SET update_time='{update_time}',
                    update_time_text='{update_time_text}',
                    status='{status}'
                WHERE task_id = '{task_id}'
                  AND task_id = '{task_id}'
                  AND room_alias = '{room_alias}'
                """.format(**record_info)
        # logger.debug(sql)
        c.execute(sql)
        self.task_db.commit()
        c.close()

    def update_rooms_tasks(self, task_info):
        """
        更新任务的状态，
        """
        sql = """
                UPDATE rooms_task
                SET update_time='{update_time}',
                    update_time_text='{update_time_text}',
                    status='{status}'
                WHERE tag_id = '{tag_id}'
                  AND task_id = '{task_id}'
        """.format(**task_info)
        c = self.task_db.cursor()
        c.execute(sql)
        self.task_db.commit()
        c.close()

    def get_task_rooms_list(self, tag_id, task_id, status):
        """
        从表rooms_records,获取room-alias 列表，
        :param tag_id:
        :param task_id:
        :return:
        """
        c = self.task_db.cursor()
        sql = "SELECT room_alias FROM rooms_records WHERE tag_id='{}' AND task_id='{}' AND status='{}'".format(tag_id,
                                                                                                               task_id,
                                                                                                               status)
        c.execute(sql)
        result = c.fetchall()
        c.close()
        return result

    def get_last_room_serialno(self, tag_id):
        """
        从数据库中获取 最后一个serialno
        :param tag_id:
        :return:
        """
        sql = f"SELECT max(room_serialno) FROM t_rooms WHERE tag_id='{tag_id}'"
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        result = c.fetchone()
        value = result[0]
        if value:
            return value
        else:
            # 数据库中没有值，则返回默认值 0
            return 0

    def get_last_friend_serialno(self, tag_id):
        """
        从表 t_friend 获取最后一个serialno
        :param conn:
        :param tag_id:
        :return:
        """
        sql = f"SELECT max(friend_serialno) FROM t_friend WHERE tag_id='{tag_id}'"
        c = self.friendinfo_db.cursor()
        c.execute(sql)
        result = c.fetchone()
        value = result[0]
        if value:
            return value
        else:
            # 数据库中没有值，则返回默认值 0
            return 0

    def get_room_task(self, wxid, tag_id):
        """
        从数据库获取群发任务，
        :param tag_id:
        :return:
        """
        # TODO: 先查询缓存中是否有任务信息，
        #  如有，就运行，
        #  如果没有就从数据库中寻找，
        #  如果数据库中有未完成的任务，则获取，
        #  如果数据库中没有任务，则自动创建，

        # 从数据库中 找是否有未完成的任务，如有，继续完成， 如没有，创建新的任务，并运行，
        # 任务状态（ 0未完成 1 已完成 2 手动完成）
        results = self.select_task(tag_id, 0)
        # logger.debug(result)
        current_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # 默认　task_id 默认为 1
        task_info = {
            "tag_id": tag_id,
            "task_type": 1,
            "task_id": 1,
            "content": "message",
            "create_time": int(time.time()),
            "create_time_text": current_datetime,
            "status": 0,
        }
        task_rooms = []
        task_message = ''
        task_id = 0
        if len(results) < 1:
            # 没有任务，创建任务，查找最后的task_id
            task_id = self.get_last_task_id(tag_id)
            task_id += 1
            logger.debug("没有任务，创建任务")
            task_message = get_task_message(wxid)
            task_info["task_id"] = task_id
            task_info["content"] = task_message
            task_message = task_message
            task_rooms = self.creat_task(task_info)
            # logger.debug("创建任务，任务总数量：{}".format(len(task_rooms)))
            logger.debug("创建任务，任务总数量：{}".format(len(task_rooms)))
        else:
            # 有任务 询问是否执行，
            for result in results:
                task_id = result[0]
                task_message = result[1]
                tip_text = "{}--{}--{}--{}".format(task_id, task_message[:10], result[2], result[3])
                logger.debug(tip_text)
            result = self.get_task_rooms_list(tag_id, task_id, 0)
            for room in result:
                task_rooms.append(room[0])
            # logger.debug("未完成任务数量：{}".format(len(task_rooms)))
            logger.debug("未完成任务数量：{}".format(len(task_rooms)))
        return task_id, task_message, task_rooms

    def sql_test(self):
        """
        测试sql,
        :return:
        """
        c = self.friendinfo_db.cursor()
        sql = "SELECT * FROM t_business_friend WHERE tag_id = '1001' AND company = '＠北京酷得少年科技 ' AND nick_name = '李悦'"
        c.execute(sql)
        values = c.fetchone()
        logger.debug(values)
        if values:
            logger.debug("True")
        else:
            logger.debug("false")

        c.close()


if __name__ == '__main__':
    # kk = oper_database("3321")
    # get_path()
    pass
